package edu.unc.comp410.colemangeer.model;

import java.io.FileNotFoundException;

import org.apache.log4j.Logger;
import org.omg.CORBA.portable.ApplicationException;
import org.omg.CORBA.portable.InputStream;

import edu.unc.comp410.colemangeer.data.CustomerGateway;
import edu.unc.comp410.colemangeer.data.CustomerGatewayEmulator;
import edu.unc.comp410.colemangeer.data.ICustomerGateway;
import edu.unc.comp410.colemangeer.data.IProductGateway;
import edu.unc.comp410.colemangeer.data.ProductGateway;
import edu.unc.comp410.colemangeer.data.ProductGatewayEmulator;

public class DataProvider {
	
	private static Logger log = Logger.getLogger( DataProvider.class );
	
	
	public IProductGateway getProductGateway() throws ApplicationException{
		return getProductGatewayOrEmulator();
	}
	
	public ICustomerGateway getCustomerGateway() throws ApplicationException{
		return getCustomerGatewayOrEmulator();
	}
	
	// Product Gateway methods
	
	private IProductGateway getProductGatewayOrEmulator() throws ApplicationException{
		IProductGateway returnObj = null;
		String logMsg;
		returnObj = new ProductGateway("customer1","classroom");
		logMsg = "DataProvider returns ProductGateway";
		
		if (returnObj==null || !returnObj.successfulDBconnection()){
			return getProductGatewayEmulator();
		}
		
		log.warn(logMsg);
		return returnObj;

	}

	private IProductGateway getProductGatewayEmulator() throws ApplicationException{
		
		IProductGateway returnObj;
		String logMsg;
		
		try {
			returnObj = new ProductGatewayEmulator();
			logMsg = "DataProvider returns ProductGatewayEmulator";
			
		} catch (FileNotFoundException e) {
			throw new ApplicationException("Couldn't get Product Gateway or Emulator", (InputStream) System.in);
		}
		
		log.warn(logMsg);
		return returnObj;
	}
	
	//CustomerGateway methods
	
	private ICustomerGateway getCustomerGatewayOrEmulator() throws ApplicationException{
		ICustomerGateway returnObj;
		String logMsg = "DataProvider returns CustomerGateway";

		returnObj = new CustomerGateway("customer1","classroom");
	

		if (returnObj==null || !returnObj.successfulDBconnection()){
			return getCustomerGatewayEmulator();
		}
		
		log.warn(logMsg);
		return returnObj;
	}
	
	private ICustomerGateway getCustomerGatewayEmulator() throws ApplicationException{
		ICustomerGateway returnObj;
		String logMsg;
		
		try {
			returnObj = new CustomerGatewayEmulator();
			logMsg = "DataProvider returns CustomerGatewayEmulator";
			
		} catch (FileNotFoundException e) {
			throw new ApplicationException("Couldn't get Customer Gateway or Emulator", (InputStream) System.in);
		}
		
		log.warn(logMsg);
		return returnObj;
	}
	
}
